const common = {}
import time from './time.js'

import Xecharts from '../../common/Xecharts.js'
common.getDomInfo = (id, callBack, thisNew) => {
	const query = uni.createSelectorQuery().in(thisNew || this);
	query
		.select('#' + id)
		.boundingClientRect()
		.exec(function(res) {
			callBack(res[0]);
		});
}
common.doTime = (date, returnTime) => {
	//date是传入的时间 monthAndHours
	let d = date ? new Date(date) : new Date();
	// console.log(d,'doTime')
	let month = (d.getMonth() + 1) < 10 ? '0' + (d.getMonth() + 1) : (d.getMonth() + 1);
	let day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate();
	let hours = d.getHours() < 10 ? '0' + d.getHours() : d.getHours();
	let min = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes();
	let sec = d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds();
	let times = ''
	if (returnTime === 'monthAndHours') {
		times = month + '/' + day + ' ' + hours + ':' + min
	} else if (returnTime === 'nosec') {
		times = d.getFullYear() + '/' + month + '/' + day + ' ' + hours + ':' + min
	} else if (returnTime === 'year') {
		times = d.getFullYear()
	} else if (returnTime === 'monthAndDay') {
		times = month + '/' + day
	} else if (returnTime === 'yearAndmonthAndDay') {
		times = d.getFullYear() + '/' + month + '/' + day
	} else if (returnTime === 'hours') {
		// #ifdef APP-PLUS
		times = d.getFullYear() + '/' + month + '/' + day + ' ' + hours + ':00:00'
		// #endif
		// #ifndef APP-PLUS
		times = d.getFullYear() + '/' + month + '/' + day + ' ' + hours + ':00:00'
		// #endif
	} else {
		// #ifdef APP-PLUS
		times = d.getFullYear() + '/' + month + '/' + day + ' ' + hours + ':' + min + ':' + sec;
		// #endif
		// #ifndef APP-PLUS
		times = d.getFullYear() + '/' + month + '/' + day + ' ' + hours + ':' + min + ':' + sec;
		// #endif
	}
	return times
}
// 报表的返回固定的值
common.getFixedValue = (list, text) => {
		let returnTxt = ''
		let arr = list.filter(v => {
			return v.elementName == text
		})
		if (arr && arr.length > 0) {
			returnTxt = arr[0].elementValue
		}
		return returnTxt
	},
	// 跳转页面
common.jumpToPage = (url,obj) => {
	uni.navigateTo({
		url: url,
		success() {
			// #ifdef APP-PLUS
			if(!obj ||(obj&&!obj.noChange)) plus.navigator.setStatusBarStyle('dark')
			// #endif
		}
	})
},
common.formatTimeUTC = (t, utc) => {
	//t传入的时间参数,utc传入的时区参数

	if (!t) return
	t = t.replace(/-/g, '/')
	//获取本地时间
	var d = new Date()
	//获得本地时区
	utc = utc ? parseFloat(utc) : d.getTimezoneOffset() / 60
	//格式化传入时间
	var time = new Date(t)
	//转换传入时间为本地时间（默认传入服务器时间为东八区时间）
	time.setHours(time.getHours() + (utc + 8))
	//输出时间
	var yy = time.getFullYear()

	var MM = time.getMonth() + 1

	MM = MM < 10 ? '0' + MM : MM

	var dd = time.getDate()

	dd = dd < 10 ? '0' + dd : dd

	var hh = time.getHours()

	hh = hh < 10 ? '0' + hh : hh

	var mm = time.getMinutes()

	mm = mm < 10 ? '0' + mm : mm

	var ss = time.getSeconds()

	ss = ss < 10 ? '0' + ss : ss

	var date = yy + '-' + MM + '-' + dd + ' ' + hh + ':' + mm + ':' + ss

	return date
},
common.formatTime = (date) => {
	//date是传入的时间
	let d = date ? new Date(date) : new Date();

	let month = (d.getMonth() + 1) < 10 ? '0' + (d.getMonth() + 1) : (d.getMonth() + 1);
	let day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate();
	let hours = d.getHours() < 10 ? '0' + d.getHours() : d.getHours();
	let min = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes();
	let sec = d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds();

	let now = new Date();
	let times = d.getFullYear() + '-' + month + '-' + day + ' ' + hours + ':' + min;
	//今年 去掉年
	if (d.getFullYear() === now.getFullYear()) {
		times = times.substring(5, times.length)
	}
	//今天 去掉天
	if (d.getFullYear() === now.getFullYear() && d.getMonth() == now.getMonth() && d.getDate() == now.getDate()) {
		times = times.substring(6, times.length)
	}
	return times
}
common.getFileSize = (file) => {
	var fileSize = '';
	if (file.size > 1024 * 1024) {
		fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
	} else {
		fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
	}
	return fileSize
}
// 时间转  2020-08-11T17:00:00  转  2020-08-11   17:00
common.tTimeTo = (time) => {
	let arr = time.split('T')
	let arr2 = arr[1].split(':')
	console.log(arr, arr2)
	return arr[0] + ' ' + arr2[0] + ':' + arr2[1]
},

/**
 * 获取上一个月
 *
 * @date 格式为yyyy-mm-dd的日期，如：2014/01/25 获取  2014-01-25
 */
common.getPreMonth = function(date) {
	var arr = (date.indexOf('-') !== -1) ? date.split('-') : date.split('/');
	var year = arr[0]; //获取当前日期的年份
	var month = arr[1]; //获取当前日期的月份
	var day = arr[2]; //获取当前日期的日
	var days = new Date(year, month, 0);
	days = days.getDate(); //获取当前日期中月的天数
	var year2 = year;
	var month2 = parseInt(month) - 1;
	if (month2 == 0) {
		year2 = parseInt(year2) - 1;
		month2 = 12;
	}
	var day2 = day;
	var days2 = new Date(year2, month2, 0);
	days2 = days2.getDate();
	if (day2 > days2) {
		day2 = days2;
	}
	if (month2 < 10) {
		month2 = '0' + month2;
	}
	var t2 = year2 + '/' + month2 + '/' + day2;
	return t2;
}

// 获取元素的宽高信息
common.getElementInfo = function(that, text) {
	uni.getSystemInfo({
		success: function(res) { // res - 各种参数
			console.log(res.windowWidth); // 屏幕的宽度 

			let info = uni.createSelectorQuery().select(text);
			info.boundingClientRect(function(data) { //data - 各种参数
				console.log(data) // 获取元素宽度
				return data
			}).exec(that)
		},
	})
}
/**
 * 获取下一个月
 *
 * @date 格式为yyyy-mm-dd的日期，如：2014/01/25 获取  2014-01-25
 */
common.getNextMonth = function(date) {

	var arr = (date.indexOf('-') !== -1) ? date.split('-') : date.split('/');
	var year = arr[0]; //获取当前日期的年份
	var month = arr[1]; //获取当前日期的月份
	var day = arr[2]; //获取当前日期的日
	var days = new Date(year, month, 0);
	days = days.getDate(); //获取当前日期中的月的天数
	var year2 = year;
	var month2 = parseInt(month) + 1;
	if (month2 == 13) {
		year2 = parseInt(year2) + 1;
		month2 = 1;
	}
	var day2 = day;
	var days2 = new Date(year2, month2, 0);
	days2 = days2.getDate();
	if (day2 > days2) {
		day2 = days2;
	}
	if (month2 < 10) {
		month2 = '0' + month2;
	}

	var t2 = year2 + '/' + month2 + '/' + day2;
	return t2;
}
// 获取指定月份的天数 getDadys(2012,2) 参数为数字类型
common.getDadys = function(whichYear, whichMonth) {
	var nextMoth = whichMonth + 1
	var nextYear = whichYear;
	if (nextMoth == 13) {
		nextMoth = 1;
		nextYear++;
	}
	var theCurrentDate = whichYear + "-" + whichMonth + "-1";
	var theNextDate = nextYear + "-" + nextMoth + "-1";
	var yearObjOne = new Date(theCurrentDate);
	var yearObjTwo = new Date(theNextDate);

	var milliseconds = yearObjTwo.getTime() - yearObjOne.getTime()
	var daymilliseconds = 3600 * 24 * 1000;
	return (milliseconds / daymilliseconds);
}

/**
 * 统一请求的返回后的提示判断
 *
 * @date 格式为{
	 api:请求名 // 必填
	 data:{},请求参数 
	 success:()=>{}
	 errorTxt:''
 }
 */
common.requestAfterToset = function(obj) {
	obj.api(obj.data || {}).then(res => {
		if (res.code === '0') {
			obj.success ? obj.success(res) : uni.navigateBack()
		} else {
			uni.showToast({
				icon: 'none',
				title: obj.errorTxt || res.msg || '请求失败'
			})
		}
	})
}
// 获取节点日期 returnType 返回的类型: timestamp时间戳
common.getNodeDay = function(returnType, date) {
	//获取本周、本季度、本月、上月的开端日期、停止日期
	var now = date ? new Date(new Date(date).toLocaleDateString()) : new Date(new Date().toLocaleDateString()); //当前日期
	var nowDayOfWeek = now.getDay(); //今天本周的第几天
	var nowDay = now.getDate(); //当前日
	var nowMonth = now.getMonth(); //当前月
	var nowYear = now.getYear(); //当前年
	nowYear += (nowYear < 2000) ? 1900 : 0; //

	var lastMonthDate = date ? new Date(new Date(date).toLocaleDateString()) : new Date(new Date().toLocaleDateString()); //上月日期
	lastMonthDate.setDate(1);
	lastMonthDate.setMonth(lastMonthDate.getMonth() - 1);
	var lastYear = lastMonthDate.getYear();
	var lastMonth = lastMonthDate.getMonth();
	var nextMonthDate = date ? new Date(new Date(date).toLocaleDateString()) : new Date(new Date().toLocaleDateString()); //上月日期
	nextMonthDate.setDate(1);
	nextMonthDate.setMonth(nextMonthDate.getMonth() + 1);
	var nextYear = nextMonthDate.getYear();
	var nextMonth = nextMonthDate.getMonth();
	//格局化日期：yyyy-MM-dd
	var formatDate = function(date) {
		if (returnType == 'timestamp' && date) {
			return date.getTime();
		}
		var myyear = date.getFullYear();
		var mymonth = date.getMonth() + 1;
		var myweekday = date.getDate();

		if (mymonth < 10) {
			mymonth = "0" + mymonth;
		}
		if (myweekday < 10) {
			myweekday = "0" + myweekday;
		}
		return (myyear + "/" + mymonth + "/" + myweekday);
	}

	//获得某月的天数
	var getMonthDays = function(myMonth) {
		var monthStartDate = new Date(nowYear, myMonth, 1);
		var monthEndDate = new Date(nowYear, myMonth + 1, 1);
		var days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24);
		return days;
	}

	//获得本季度的开端月份
	var getQuarterStartMonth = function() {
		var quarterStartMonth = 0;
		if (nowMonth < 3) {
			quarterStartMonth = 0;
		}
		if (2 < nowMonth && nowMonth < 6) {
			quarterStartMonth = 3;
		}
		if (5 < nowMonth && nowMonth < 9) {
			quarterStartMonth = 6;
		}
		if (nowMonth > 8) {
			quarterStartMonth = 9;
		}
		return quarterStartMonth;
	}
	
	var getDayEndDate = function() {
		var dayEndDate = new Date(nowYear, nowMonth, 0);
		return formatDate(dayEndDate);
	}
	// 获得昨天的日期
	var getDayPreDate = function(){
		var dayPreDate = new Date(nowYear, nowMonth,nowDay - 1)
		return formatDate(dayPreDate);
	}
	// 获得前天的日期
	var getDayBeforeDate = function(){
		var dayPreDate = new Date(nowYear, nowMonth,nowDay - 2)
		return formatDate(dayPreDate);
	}
	// 获取前几天的日期  dateIndex
	var getDayBefore_X_Date = function(num){
		var dayPreDate = new Date(nowYear, nowMonth,nowDay - num)
		return formatDate(dayPreDate);
	}
	// 获得今天的日子
	var getDayNowDate = function(){
		var dayNowDate = new Date(nowYear, nowMonth, nowDay)
		return formatDate(dayNowDate)
	}
	var getDayNumDate = function(num){
		var dayNumDate = new Date(nowYear, nowMonth,nowDay+num)
		return formatDate(dayNumDate)
	}
	//获得本周的开端日期
	var getWeekStartDate = function() {
		var weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek);
		return formatDate(weekStartDate);
	}

	//获得本周的停止日期
	var getWeekEndDate = function() {
		var weekEndDate = new Date(nowYear, nowMonth, nowDay + (7 - nowDayOfWeek));
		return formatDate(weekEndDate);
	}

	//获得本月的开端日期
	var getMonthStartDate = function() {
		var monthStartDate = new Date(nowYear, nowMonth, 1);
		return formatDate(monthStartDate);
	}

	//获得本月的停止日期
	var getMonthEndDate = function() {
		var monthEndDate = new Date(nowYear, nowMonth, getMonthDays(nowMonth));
		return formatDate(monthEndDate);
	}

	//获得上月开端时候
	var getLastMonthStartDate = function() {
		var lastMonthStartDate = new Date(lastMonth == 11 ? nowYear - 1 : nowYear, lastMonth, 1);
		return formatDate(lastMonthStartDate);
	}

	//获得上月停止时候
	var getLastMonthEndDate = function() {
		var lastMonthEndDate = new Date(nowYear, lastMonth, getMonthDays(lastMonth));
		return formatDate(lastMonthEndDate);
	}
	//获得下月开端时候
	var getNextMonthStartDate = function() {
		var nextMonthStartDate = new Date(nowYear, nextMonth, 1);
		return formatDate(nextMonthEndDate);
	}
	
	//获得下月停止时候
	var getNextMonthEndDate = function() {
		var nextMonthEndDate = new Date(nextMonth == 0 ? nowYear + 1 : nowYear, nextMonth, getMonthDays(nextMonth));
		return formatDate(nextMonthEndDate);
	}

	//获得本季度的开端日期
	var getQuarterStartDate = function() {
		var quarterStartDate = new Date(nowYear, getQuarterStartMonth(), 1);
		return formatDate(quarterStartDate);
	}

	//或的本季度的停止日期
	var getQuarterEndDate = function() {
		var quarterEndMonth = getQuarterStartMonth() + 2;
		var quarterStartDate = new Date(nowYear, quarterEndMonth, getMonthDays(quarterEndMonth));
		return formatDate(quarterStartDate);
	}
	//获取本年的开端日期
	var getYearStartDate = function() {
		var yearStartDate = new Date(nowYear, 0, 1);
		return formatDate(yearStartDate);
	}
	//获取本年的停止日期
	var getYearEndDate = function() {
		var yearEndDate = new Date(nowYear + 1, 0, -1);
		return formatDate(yearEndDate);
	}
	return {
		getDayEndDate,
		getWeekStartDate,
		getWeekEndDate,
		getMonthStartDate,
		getMonthEndDate,
		getLastMonthStartDate,
		getNextMonthEndDate,
		getYearStartDate,
		getYearEndDate,
		getQuarterStartDate,
		getQuarterEndDate,
		getDayPreDate,//获取昨天
		getDayBeforeDate,// 获取前天
		getDayNowDate,
		getDayBefore_X_Date,
		getDayNumDate,//获取前后天的时间
	}
}
// 秒转换成天时分
common.secondFormat = function(s, returnType) {
	var day = Math.floor(s / (24 * 3600)); // Math.floor()向下取整 
	var hour = Math.floor((s - day * 24 * 3600) / 3600);
	var minute = Math.floor((s - day * 24 * 3600 - hour * 3600) / 60);
	var second = s - day * 24 * 3600 - hour * 3600 - minute * 60;
	console.log((day > 0 && day + "d"), day, hour, minute, second)
	if (returnType == 'dhm') {//天时分
		return (day > 0 ? day + "d" : '') + (hour > 0 ? hour + "h" : '') + (minute > 0 ? minute + "m" : '')
	} else if (returnType == 'cn') {//中文
		return (day > 0 ? day + "天" : '') + (hour > 0 ? hour + "时" : '') + (minute > 0 ? minute + "分" : '') + (second > 0 ?
			second + "秒" : '');
	}
	return (day > 0 ? day + "d" : '') + (hour > 0 ? hour + "h" : '') + (minute > 0 ? minute + "m" : '') + second + "s";
}


// js中获取当前时间前（N分钟）10分钟时间   format=  Y/M/D h:m  timestamp
common.getNowFormatDate = function(preTime = 10,format = 'Y/M/D h:m') {
	var date = new Date();
	var seperator1 = "/";
	var seperator2 = ":";
	//前十分钟时间
	var minutes = parseInt(preTime + '');

	var interTimes = minutes * 60 * 1000;

	var interTimes = parseInt(interTimes);
	date = new Date(Date.parse(date) - interTimes);

	var month = date.getMonth() + 1;
	var strDate = date.getDate();
	var hour = date.getHours();
	var minutes = date.getMinutes();
	if (month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if (strDate >= 0 && strDate <= 9) {
		strDate = "0" + strDate;
	}
	if (hour >= 0 && hour <= 9) {
		hour = "0" + hour;
	}
	if (minutes >= 0 && minutes <= 9) {
		minutes = "0" + minutes;
	}
	var currentdate =''
	if(format=='Y/M/D h:m'){
		 currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate +
			" " + hour + seperator2 + minutes ;
	}else if (format=='Y/M/D'){
		currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate 
					
	}else if (format=='Y/M'){
		currentdate = date.getFullYear() + seperator1 + month
					
	}else if(format=='timestamp'){
		let currentdateBytimestamp = date.getFullYear() + seperator1 + month + seperator1 + strDate +
			" " + hour + seperator2 + minutes ;
		currentdate = time.txtToTimeNum(currentdateBytimestamp)
	}
		  // seperator2+ date.getSeconds()
	return currentdate;
}





// 求平均值
common.arrAverageNum2 = function(arr) {
	var sum = eval(arr.join("+"));
	return ~~(sum / arr.length * 100) / 100;
}

// 深度判断两个对象是否相等
common.deepCompare = function (x, y){
        var i, l, leftChain, rightChain;

        function compare2Objects(x, y) {
            var p;

            // remember that NaN === NaN returns false
            // and isNaN(undefined) returns true
            if (isNaN(x) && isNaN(y) && typeof x === 'number' && typeof y === 'number') {
                return true;
            }

            // Compare primitives and functions.     
            // Check if both arguments link to the same object.
            // Especially useful on the step where we compare prototypes
            if (x === y) {
                return true;
            }

            // Works in case when functions are created in constructor.
            // Comparing dates is a common scenario. Another built-ins?
            // We can even handle functions passed across iframes
            if ((typeof x === 'function' && typeof y === 'function') ||
                (x instanceof Date && y instanceof Date) ||
                (x instanceof RegExp && y instanceof RegExp) ||
                (x instanceof String && y instanceof String) ||
                (x instanceof Number && y instanceof Number)) {
                return x.toString() === y.toString();
            }

            // At last checking prototypes as good as we can
            if (!(x instanceof Object && y instanceof Object)) {
                return false;
            }

            if (x.isPrototypeOf(y) || y.isPrototypeOf(x)) {
                return false;
            }

            if (x.constructor !== y.constructor) {
                return false;
            }

            if (x.prototype !== y.prototype) {
                return false;
            }

            // Check for infinitive linking loops
            if (leftChain.indexOf(x) > -1 || rightChain.indexOf(y) > -1) {
                return false;
            }

            // Quick checking of one object being a subset of another.
            // todo: cache the structure of arguments[0] for performance
            for (p in y) {
                if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
                    return false;
                } else if (typeof y[p] !== typeof x[p]) {
                    return false;
                }
            }

            for (p in x) {
                if (y.hasOwnProperty(p) !== x.hasOwnProperty(p)) {
                    return false;
                } else if (typeof y[p] !== typeof x[p]) {
                    return false;
                }

                switch (typeof(x[p])) {
                    case 'object':
                    case 'function':

                        leftChain.push(x);
                        rightChain.push(y);

                        if (!compare2Objects(x[p], y[p])) {
                            return false;
                        }

                        leftChain.pop();
                        rightChain.pop();
                        break;

                    default:
                        if (x[p] !== y[p]) {
                            return false;
                        }
                        break;
                }
            }

            return true;
        }

        if (arguments.length < 1) {
            return true; //Die silently? Don't know how to handle such case, please help...
            // throw "Need two or more arguments to compare";
        }

        for (i = 1, l = arguments.length; i < l; i++) {

            leftChain = []; //Todo: this can be cached
            rightChain = [];

            if (!compare2Objects(arguments[0], arguments[i])) {
                return false;
            }
        }

        return true;
    }


export default {
	common,
  time,
  Xecharts,
}
